package com.ghbank.rdws.common.aop;

import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.ghbank.rdws.common.utils.IPUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * Web层日志切面
 * @author xudong.liu
 * @date 2019年4月5日
 */
@Aspect
@Order(5)
@Component
@Slf4j
public class WebLogAspect {
    private ThreadLocal<Long> startTime = new ThreadLocal<>();
   
    @Pointcut("execution(public * com.ghbank.rdws.*.controller..*.*(..))")
    public void webLog(){}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());

        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 记录下请求内容
        StringBuilder sb = new StringBuilder();
        sb.append("URL:").append(request.getRequestURL().toString())
           .append(" HTTP_METHOD:").append(request.getMethod())
           .append(" IP: ").append(IPUtils.getIpAddr(request))
           .append(" ARGS: ").append(Arrays.toString(joinPoint.getArgs()));
        log.info(sb.toString());

    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        StringBuilder sb = new StringBuilder();
        // 处理完请求，返回内容
        sb.append("RESPONSE: ").append(ret)
            .append(" SPEND TIME: ").append(System.currentTimeMillis() - startTime.get());
        log.info(sb.toString());
    }
}
